<template>
  <view class="personalData allColumnCenter">
    <header-title ref="headerTitle" isDisplayBack title="个人资料" is-fixed background="#f5f5f5"
                  @getPageHeight="getPageHeight"></header-title>
    <view :style="{height:`${headerHeight}px`}"></view>
    <single-gap title="头像" margin="25rpx 0 0 0" @elementClick="goAvatarList">
      <view class="personalData_avatar row items-center justify-between">
        <image-avater :src="personalData.avatar" :width="76" :height="76"></image-avater>
        <image class="personalData_avatar_image" src="/static/shiqin-images/arrow_right.png"></image>
      </view>
    </single-gap>
    <single-gap title="姓名" margin="25rpx 0 0 0" @elementClick="openNamePopup">
      <view class="personalData_avatar row items-center justify-between">
        <text class="personalData_avatar_text">
          {{ personalData.username || '未设置' }}
        </text>
        <image class="personalData_avatar_image" src="/static/shiqin-images/arrow_right.png"></image>
      </view>
    </single-gap>
    <single-gap title="关系" margin="25rpx 0 0 0" color="#FF4206" @elementClick="openRelationshipPopUp">
      <view class="personalData_avatar row items-center justify-between">
        <text class="personalData_avatar_text">
          {{ personalData.remark }}
        </text>
        <image class="personalData_avatar_image" src="/static/shiqin-images/arrow_right.png"></image>
      </view>
    </single-gap>
    <single-gap title="生日" margin="25rpx 0 0 0" @elementClick="openBetterCalendar">
      <view class="personalData_avatar row items-center justify-between">
        <text class="personalData_avatar_text">
          {{ personalData.birthday.date || '未设置' }}
        </text>
        <image class="personalData_avatar_image" src="/static/shiqin-images/arrow_right.png"></image>
      </view>
    </single-gap>
    <single-gap title="纪念日" margin="25rpx 0 0 0" @elementClick="openCommemoration">
      <view class="personalData_avatar row items-center justify-between">
        <text class="personalData_avatar_text">
          去编辑
        </text>
        <image class="personalData_avatar_image" src="/static/shiqin-images/arrow_right.png"></image>
      </view>
    </single-gap>
    <single-gap title="提醒设置" margin="25rpx 0 0 0"
                @elementClick="$nav.navigateTo('/pages/shiqinUserPage/reminderSettings',{member_id:personalData.id})">
      <view class="personalData_avatar row items-center justify-end">
        <image class="personalData_avatar_image" src="/static/shiqin-images/arrow_right.png"></image>
      </view>
    </single-gap>

    <!--    <single-gap title="手机号" margin="25rpx 0 0 0">-->
    <!--      <view class="personalData_avatar row items-center justify-between">-->
    <!--        <text class="personalData_avatar_text">-->
    <!--          {{ !!personalData.phone ? personalData.phone : '未绑定' }}-->
    <!--        </text>-->
    <!--        <image class="personalData_avatar_image" src="/static/shiqin-images/arrow_right.png"></image>-->
    <!--      </view>-->
    <!--    </single-gap>-->

    <single-gap title="更多" v-if="!ismore" margin="25rpx 0 0 0" @elementClick="ismore = true">
      <view class="personalData_avatar row items-center justify-end">
        <image class="personalData_avatar_image" src="/static/shiqin-images/arrow_right.png"></image>
      </view>
    </single-gap>
    <single-gap title="签名" v-if="ismore" margin="25rpx 0 0 0" @elementClick="goSignature">
      <view class="personalData_avatar row items-center justify-between">
        <text class="personalData_avatar_text">
          {{ personalData.autograph || '未设置' }}
        </text>
        <image class="personalData_avatar_image" src="/static/shiqin-images/arrow_right.png"></image>
      </view>
    </single-gap>
    <single-gap title="祖籍地" v-if="ismore" margin="25rpx 0 0 0" @elementClick="openAncestral(1)">
      <view class="personalData_avatar row items-center justify-between">
        <text class="personalData_avatar_text">
          {{ personalData.ancestral || '未设置' }}
        </text>
        <image class="personalData_avatar_image" src="/static/shiqin-images/arrow_right.png"></image>
      </view>
    </single-gap>
    <single-gap title="现居地" v-if="ismore" margin="25rpx 0 0 0" @elementClick="openAncestral(2)">
      <view class="personalData_avatar row items-center justify-between">
        <text class="personalData_avatar_text">
          {{ personalData.current_address || '未设置' }}
        </text>
        <image class="personalData_avatar_image" src="/static/shiqin-images/arrow_right.png"></image>
      </view>
    </single-gap>
    <single-gap title="血型" v-if="ismore" margin="25rpx 0 0 0" @elementClick="bloodTypeShow = true">
      <view class="personalData_avatar row items-center justify-between">
        <text class="personalData_avatar_text">
          {{ personalData.blood_type || '未设置' }}
        </text>
        <image class="personalData_avatar_image" src="/static/shiqin-images/arrow_right.png"></image>
      </view>
    </single-gap>
    <single-gap title="学历" v-if="ismore" margin="25rpx 0 0 0" @elementClick="academicQualificationsShow = true">
      <view class="personalData_avatar row items-center justify-between">
        <text class="personalData_avatar_text">
          {{ personalData.education || '未设置' }}
        </text>
        <image class="personalData_avatar_image" src="/static/shiqin-images/arrow_right.png"></image>
      </view>
    </single-gap>
    <single-gap title="职业" v-if="ismore" margin="25rpx 0 0 0" @elementClick="openOccupationalPopup">
      <view class="personalData_avatar row items-center justify-between">
        <text class="personalData_avatar_text">
          {{ personalData.career || '未设置' }}
        </text>
        <image class="personalData_avatar_image" src="/static/shiqin-images/arrow_right.png"></image>
      </view>
    </single-gap>
    <textare-gap title="备注" margin="25rpx 0 0 0" :value="personalData.notes" @save="save"></textare-gap>
    <view class="personalData_bottomEdit mt-72">
      <text class="personalData_bottomEdit_text">
        删除{{personalData.username}}
      </text>
    </view>
    <view style="height: 150rpx"></view>

    <first_popup ref="relationshipPopup">
      <template>
        <scroll-view :scroll-y="true" class="relationshipPopup ">
          <view class="relationshipPopup_all justify-between mt-44">
            <view class="relationshipPopup_all_list allRowCenter" v-for="(item,index) in relationshipsList"
                  :key="index" :style="{
                    background:relationshipsIndex == index ? '#FF4206':'#E5E5E5'
                  }" @click="selectRelation(index)">
              <text class="relationshipPopup_all_list_text" :style="{
                color:relationshipsIndex == index ? '#FFFFFF' :item.sexFlag ? '#292929': '#FF4206'
              }">{{ item.name }}
              </text>
            </view>
          </view>
        </scroll-view>
      </template>
      <template v-slot:bottomContent>
        <view class="relationshipPopup_bottomContent allRowCenter  mt-48 mb-120 mr-19">
          <input class="relationshipPopup_bottomContent_input" :value="callValue" placeholder="自定义填写"
                 placeholder-class="relationshipPopup_bottomContent_placeholder" @input="callInput"></input>
        </view>
      </template>
    </first_popup>

    <!-- 名字修改 -->
    <first_popup ref="namePopUp">
      <template>
        <view class="familyMemberPopUp allColumnCenter">
          <view class="familyMemberPopUp_editInfo row items-center justify-between mt-64">
            <view class="familyMemberPopUp_editInfo_left allRowCenter">
              <input type="text" :value="namePopupFrom.suername" placeholder="尊姓"
                     placeholder-class="familyMemberPopUp_editInfo_placeholder" @input="suernameInput"
                     @blur="surnameBlur">
            </view>
            <view class="familyMemberPopUp_editInfo_right allRowCenter">
              <input type="text" :value="namePopupFrom.name" placeholder="大名"
                     placeholder-class="familyMemberPopUp_editInfo_placeholder" @input="nameInput" @blur="nameBlur">
            </view>
          </view>
        </view>
      </template>
    </first_popup>
    <!-- 选择生日 -->
    <better-calendar class="z-999"
                     ref="betterCalendarRef"
                     :showCalendar="showCalendar"
                     @confirm="updateMemberBirthday"
                     @cancel="showCalendar = false"
    ></better-calendar>
    <!-- 选择现居地/祖籍地 -->
    <areaWindow ref="areaWindow" :cityShow="2" :display="areaWindowDisplay" :address="addressInfo"
                @submit="OnChangeAddress"
                @changeClose="changeClose"></areaWindow>
    <!-- 选择血型 -->
    <u-select title="请选择血型" v-model="bloodTypeShow" :list="bloodList" @cancel="bloodTypeShow = false"
              @confirm="bloodTypeConfirm"></u-select>
    <!-- 选择学历 -->
    <u-select title="请选择学历" v-model="academicQualificationsShow" :list="academicQualificationsList"
              @cancel="academicQualificationsShow = false" @confirm="academicQualificationsConfirm"></u-select>
    <!--  职业修改  -->
    <first_popup ref="occupationalPopup">
      <template>
        <view class="occupationPopup">
          <input :value="occupation" class="occupationPopup_input" placeholder="请输入职业名称" @input="occupationInput"
                 @blur="occupationBlur" maxlength="10"></input>
        </view>
      </template>
    </first_popup>
  </view>
</template>

<script>
import HeaderTitle from "../../components/shiqinComponents/pageComponents/headerTitle.vue";
import SingleGap from "../../components/shiqinComponents/shiqin_pageGap/singleGap.vue";
import ImageAvater from "../../components/shiqinComponents/pageComponents/imageAvater.vue";
import TextareGap from "../../components/shiqinComponents/shiqin_pageGap/textareGap.vue";
import First_popup from "../../components/shiqinComponents/shiqin_globalPopUps/first_popup.vue";
import BetterCalendar from "../../components/shiqinComponents/timePick/timePick.vue";
import areaWindow from '../../components/areaWindow';
import {
  getAppellationList,
  getPersonalData,
  setMemberRemark,
  updateMemberBirthday,
  updateMemberImage, updateUsername
} from "../../api/shiqinAPI";

import colors from '../../mixins/color.js';

export default {
  components: {BetterCalendar, First_popup, TextareGap, ImageAvater, SingleGap, HeaderTitle, areaWindow},
  mixins: [colors],
  data() {
    const INIT_DAY_TYPE = "solar";
    const INIT_DAY_TIMESTAMP = this.$dayjs().valueOf();
    const INIT_DAY = this.$dayjs().format("YYYY-MM-DD");
    return {
      // 头部高度
      headerHeight: 0,
      // 是否显示更多
      ismore: false,
      // 关系列表
      relationshipsList: [],
      relationshipsIndex: 0,
      // 关系自定义填写
      callValue: '',
      showCalendar: false,
      date: {
        type: INIT_DAY_TYPE, // 类型
        timestamp: INIT_DAY_TIMESTAMP, // 时间戳
        solarDate: INIT_DAY, // 公历日期 - 文本（2000-1-1）
        lunarDate: "", // 农历日期 - 文本（己卯年冬月廿五(2000-1-1)）
        lunarDateNumber: "", // 农历生日的数字写法（1999-12-25）
      },
      options: {},
      // 个人用户信息
      personalData: {},
      // 弹窗姓名输入框
      namePopupFrom: {
        suername: '',
        name: ''
      },
      areaWindowDisplay: false,
      addressInfo: [],
      selectAddress: 1,
      // 血型
      bloodTypeShow: false,
      // 血型列表
      bloodList: [
        {
          value: 'A',
          label: 'A'
        },
        {
          value: 'B',
          label: 'B'
        },
        {
          value: 'AB',
          label: 'AB'
        },
        {
          value: 'O',
          label: 'O'
        }
      ],
      // 学历
      academicQualificationsShow: false,
      // 学历列表
      academicQualificationsList: [
        {
          value: '无',
          label: '无'
        },
        {
          value: '小学',
          label: '小学'
        },
        {
          value: '初中',
          label: '初中'
        },
        {
          value: '高中',
          label: '高中'
        },
        {
          value: '专科',
          label: '专科'
        },
        {
          value: '本科',
          label: '本科'
        },
        {
          value: '研究生',
          label: '研究生'
        },
        {
          value: '博士',
          label: '博士'
        },
        {
          value: '博士后',
          label: '博士后'
        }
      ],
      // 职业输入框
      occupation: '',
    };
  },
  onLoad(options) {
    this.options = options
  },
  onReady() {
    this.$nextTick(() => {
      this.$refs.headerTitle.getPageHeight()
    })
  },
  onShow() {
    // 获取关系列表
    this.getRelationshipsList()
    // 获取个人资料
    this.getPersonalData(this.options.member_id)
  },
  methods: {
    // 处理用户名的输入事件
    suernameInput(e) {
      if (e.target.value.length > 1) {
        let arr
        arr = e.target.value.match(/[\u4e00-\u9fa5]/g)
        if (!!arr) {
          this.$set(this.namePopupFrom, 'suername', arr.join('').substring(0, 2))
        } else {
          this.$set(this.namePopupFrom, 'suername', '')
        }
      }
    },
    // 用于处理用户名的输入失去焦点事件
    surnameBlur(e) {
      if (e.target.value.length > 0) {
        let arr
        arr = e.target.value.match(/[\u4e00-\u9fa5]/g)
        if (!!arr) {
          this.$set(this.namePopupFrom, 'suername', arr.join('').substring(0, 2))
        } else {
          this.$set(this.namePopupFrom, 'suername', '')
        }
      }
    },
    nameInput(e) {
      if (e.target.value.length > 1) {
        let arr
        arr = e.target.value.match(/[\u4e00-\u9fa5]/g)
        if (!!arr) {
          this.$set(this.namePopupFrom, 'name', arr.join('').substring(0, 4))
        } else {
          this.$set(this.namePopupFrom, 'name', '')
        }
      }
    },
    nameBlur(e) {
      if (e.target.value.length > 0) {
        let arr
        arr = e.target.value.match(/[\u4e00-\u9fa5]/g)
        if (!!arr) {
          this.$set(this.namePopupFrom, 'name', arr.join('').substring(0, 4))
        } else {
          this.$set(this.namePopupFrom, 'name', '')
        }
      }
    },
    getPageHeight(number) {
      this.headerHeight = number
    },
    // 打开设置关系弹窗
    openRelationshipPopUp() {
      this.$refs.relationshipPopup.openPopup({
        title: '设置关系',
        maskClick: false,
        bottomContentWidth: '143rpx',
        confirm: () => {
          setMemberRemark({
            member_id: this.personalData.id,
            remark: this.relationshipsIndex != -1 ? this.relationshipsList[this.relationshipsIndex].name : this.callValue
          }).then(res => {
            console.log(res)
            if (res.status == 200) {
              this.getPersonalData(this.personalData.id)
              this.$refs.relationshipPopup.closePopup()
              this.callValue = ''
              this.relationshipsIndex = 0
              uni.showToast({
                title: '设置成功',
                icon: 'none'
              })
            } else {
              uni.showToast({
                title: res.msg,
                icon: 'none'
              })
            }
          })
        }
      })
    },
    //
    openBetterCalendar() {
      this.showCalendar = true;
    },

    async selectDate(e) {
      this.date = await {
        type: e.type,
        timestamp: this.$dayjs(e.solarDate).valueOf(),
        solarDate: e.solarDate,
        lunarDate: e.lunarDate,
        lunarDateNumber: e.lunarDateNumber,
        isLeap: e.isLeap, // 一年里是否有闰月
      };
      this.form.dateBirth = e.solarDate
      this.showCalendar = false;
    },

    // 获取个人资料
    async getPersonalData(member_id) {
      let {data} = await getPersonalData({member_id})
      this.personalData = data
    },
    // 获取关系列表
    async getRelationshipsList() {
      let {data} = await getAppellationList()
      this.relationshipsList = data.list
    },
    // 选中关系名称
    selectRelation(index) {
      this.callValue = ''
      this.relationshipsIndex = index
    },
    // 自定义关系名称
    callInput(e) {
      this.relationshipsIndex = -1
      this.callValue = e.target.value
    },
    // 修改成员生日
    async updateMemberBirthday(e) {
      let {status, msg} = await updateMemberBirthday({
        member_id: this.personalData.id,
        type: e.type == 'lunar' ? 1 : 2,
        birthday: e.solarDate
      })
      if (status == 200) {
        uni.showToast({
          title: '修改成功',
          icon: 'none'
        })
        this.getPersonalData(this.personalData.id)
        this.showCalendar = false;
      } else {
        uni.showToast({
          title: msg,
          icon: 'none'
        })
      }
    },
    // 选择头像
    goAvatarList() {
      this.$nav.navigateTo('/pages/shiqinUserPage/avatarsList', {member_id: this.personalData.id})
    },
    // 修改名字
    openNamePopup() {
      this.$refs.namePopUp.openPopup({
        title: '修改姓名',
        maskClick: false,
        confirm: async () => {
          if (!this.namePopupFrom.suername) {
            uni.showToast({
              title: '姓氏尚未填写',
              icon: 'none'
            })
            return
          }
          if (!this.namePopupFrom.name) {
            uni.showToast({
              title: '名称尚未填写',
              icon: 'none'
            })
            return
          }
          let {status, msg} = await updateUsername({
            member_id: this.personalData.id,
            surname: this.namePopupFrom.suername,
            daimyo: this.namePopupFrom.name
          })
          if (status == '200') {
            uni.showToast({
              title: '修改成功',
              icon: 'none'
            })
            this.$refs.namePopUp.closePopup()
            this.namePopupFrom.name = ''
            this.namePopupFrom.suername = ''
            this.getPersonalData(this.personalData.id)
          } else {
            uni.showToast({
              title: msg,
              icon: 'none'
            })
          }
        }
      })
    },
    // 修改签名
    goSignature() {
      this.$nav.navigateTo('/pages/shiqinUserPage/signature', {member_id: this.personalData.id})
    },
    // 添加纪念日
    openCommemoration() {
      this.$nav.navigateTo('/pages/familyAnniversary/anniversary', {is_flag: 1, member_id: this.personalData.id})
    },
    // 选择地址弹窗
    openAncestral(index) {
      this.selectAddress = index
      if (this.selectAddress == 1) {
        this.addressInfo = !!this.personalData.city_list ? this.personalData.city_list : []
      } else {
        this.addressInfo = !!this.personalData.residence_list ? this.personalData.residence_list : []
      }
      this.areaWindowDisplay = true
    },
    changeClose() {
      this.areaWindowDisplay = false
    },
    async OnChangeAddress(address) {
      if (this.selectAddress == 1) {
        let {status, msg} = await updateMemberImage({
          member_id: this.personalData.id,
          city_list: address,
          ancestral: address.map(v => v.label).join('/')
        })
        if (status == 200) {
          uni.showToast({
            title: '修改成功',
            icon: 'none'
          })
          this.getPersonalData(this.personalData.id)
          this.areaWindowDisplay = false
        } else {
          uni.showToast({
            title: msg,
            icon: 'none'
          })
        }
      } else {
        let {status, msg} = await updateMemberImage({
          member_id: this.personalData.id,
          residence_list: address,
          current_address: address.map(v => v.label).join('/')
        })
        if (status == 200) {
          uni.showToast({
            title: '修改成功',
            icon: 'none'
          })
          this.getPersonalData(this.personalData.id)
          this.areaWindowDisplay = false
        } else {
          uni.showToast({
            title: msg,
            icon: 'none'
          })
        }
      }
    },
    // 确定选择血型
    async bloodTypeConfirm(e) {
      let {status, msg} = await updateMemberImage({
        member_id: this.personalData.id,
        blood_type: e[0].value
      })
      if (status == 200) {
        uni.showToast({
          title: '修改成功',
          icon: 'none'
        })
        this.getPersonalData(this.personalData.id)
        this.bloodTypeShow = false
      } else {
        uni.showToast({
          title: msg,
          icon: 'none'
        })
      }
    },
    // 确定选择学历
    async academicQualificationsConfirm(e) {
      let {status, msg} = await updateMemberImage({
        member_id: this.personalData.id,
        education: e[0].value
      })
      if (status == 200) {
        uni.showToast({
          title: '修改成功',
          icon: 'none'
        })
        this.getPersonalData(this.personalData.id)
        this.academicQualificationsShow = false
      } else {
        uni.showToast({
          title: msg,
          icon: 'none'
        })
      }
    },
    // 设置职业
    openOccupationalPopup() {
      this.$refs.occupationalPopup.openPopup({
        title: '修改职业',
        maskClick: false,
        confirm: async () => {
          if (!this.occupation) {
            uni.showToast({
              title: '职业尚未填写',
              icon: 'none'
            })
            return
          }
          let {status, msg} = await updateMemberImage({
            member_id: this.personalData.id,
            career: this.occupation
          })
          if (status == 200) {
            uni.showToast({
              title: '修改成功',
              icon: 'none'
            })
            this.occupation = ''
            this.getPersonalData(this.personalData.id)
            this.$refs.occupationalPopup.closePopup()
          } else {
            uni.showToast({
              title: msg,
              icon: 'none'
            })
          }
        }
      })
    },
    occupationInput(e) {
      this.occupation = e.target.value
    },
    occupationBlur(e) {
      this.occupation = e.target.value
    },
    async save(value) {
      if (!value) {
        uni.showToast({
          title: '备注尚未填写',
          icon: 'none'
        })
        return
      }
      let {status, msg} = await updateMemberImage({
        member_id: this.personalData.id,
        notes: value
      })
      if (status == 200) {
        uni.showToast({
          title: '修改成功',
          icon: 'none'
        })
        this.getPersonalData(this.personalData.id)
      } else {
        uni.showToast({
          title: msg,
          icon: 'none'
        })
      }
    }
  },
}
</script>

<style lang="scss" scoped>
.personalData {
  width: 750rpx;
  min-height: 100vh;
  background: $secondaryPages;

  .personalData_avatar {
    width: 489rpx;

    .personalData_avatar_image {
      width: 30rpx;
      height: 30rpx;
    }

    .personalData_avatar_text {
      font-family: PingFang SC, PingFang SC;
      font-weight: 500;
      font-size: 28rpx;
      color: #A0A0A0;
    }
  }

  .personalData_bottomEdit {
    .personalData_bottomEdit_text {
      font-family: PingFang SC, PingFang SC;
      font-weight: 500;
      font-size: 24rpx;
      color: #A0A0A0;
    }
  }

  .relationshipPopup {
    width: 556rpx;
    max-height: 846rpx;

    .relationshipPopup_all {
      width: 556rpx;
      display: grid;
      grid-template-columns: repeat(3, 168rpx);
      grid-row-gap: 26rpx;

      .relationshipPopup_all_list {
        width: 168rpx;
        height: 63rpx;
        background: #E5E5E5;
        border-radius: 41rpx 41rpx 41rpx 41rpx;
      }
    }
  }

  .relationshipPopup_bottomContent {
    width: 393rpx;
    height: 80rpx;
    background: #FFFFFF;
    border-radius: 40rpx 40rpx 40rpx 40rpx;
    border: 1rpx solid #707070;

    .relationshipPopup_bottomContent_input {
      text-align: center;
    }

    .relationshipPopup_bottomContent_placeholder {
      font-family: PingFang SC, PingFang SC;
      font-weight: 500;
      font-size: 30rpx;
      color: #A0A0A0;
    }
  }

  .familyMemberPopUp {
    width: 506rpx;

    .familyMemberPopUp_scrollView {
      width: 506rpx;
      overflow: hidden;
      white-space: nowrap;

      .familyMemberPopUp_scrollView_list {
        display: inline-block;
      }
    }

    .familyMemberPopUp_editInfo {
      width: 506rpx;

      .familyMemberPopUp_editInfo_left {
        width: 239rpx;
        height: 80rpx;
        background: #FFFFFF;
        border-radius: 40rpx 40rpx 40rpx 40rpx;
        border: 2rpx solid #707070;

        input {
          text-align: center;
        }
      }

      .familyMemberPopUp_editInfo_right {
        width: 239rpx;
        height: 80rpx;
        background: #FFFFFF;
        border-radius: 40rpx 40rpx 40rpx 40rpx;
        border: 2rpx solid #707070;

        input {
          text-align: center;
        }
      }

      .familyMemberPopUp_editInfo_placeholder {
        font-family: PingFang SC, PingFang SC;
        font-weight: 500;
        font-size: 28rpx;
        color: #A0A0A0;
      }
    }
  }

  .occupationPopup {
    width: 556rpx;

    .occupationPopup_input {
      width: 556rpx;
      height: 80rpx;
      border: 2rpx solid #707070;
      border-radius: 20rpx;
      text-align: center;
    }
  }
}
</style>
